package cn.bonoon.kernel.expression.resolver;

import cn.bonoon.kernel.expression.IExpressionResolver;
import cn.bonoon.kernel.expression.StandardExpressionParser;

public abstract class BaseExpressionResolver implements IExpressionResolver{
	
	private final String command;
	private final int commandLength;
	
	protected BaseExpressionResolver(String command){
		this.command = command;
		this.commandLength = command.length();
	}
	
	public static IExpressionResolver factory(){
		return new IExpressionResolver(){
			
			private IExpressionResolver[] resolvers = {
				new FieldExpressionResolver(),
				new ModelExpressionResolver(),
				new UserExpressionResolver(),
				new SesssionExpressionResolver()
			};
			
			@Override
			public boolean resolver(String expression, StandardExpressionParser seParser) throws Exception{
				for(IExpressionResolver resolver : resolvers){
					if(resolver.resolver(expression, seParser)){
						return true;
					}
				}
				return false;
			}
			
		};
	}
	
	@Override
	public boolean resolver(String expression, StandardExpressionParser seParser) throws Exception{
		if(expression.startsWith(command) && expression.charAt(commandLength) == ' '){
			String[] commands = expression.split(" ");
			_internalResolver(seParser, commands);
			return true;
		}
		return false;
	}
	
	/**
	 * 生成查询语句的表达式；如果子类需要处理特殊情况，则可以重写，如直接赋值等
	 * @param seParser
	 * @param commands
	 */
	protected void _internalResolver(StandardExpressionParser seParser, String[] commands)throws Exception{
		seParser.getExpression().append('?');
	}
}
